package com.deyang.workflow.service.impl;

import cn.hutool.core.date.DatePattern;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.deyang.workflow.entity.WorkOrderBase;
import com.deyang.workflow.entity.WorkOrderDetails;
import com.deyang.workflow.mapper.WorkOrderBaseMapper;
import com.deyang.workflow.mapper.WorkOrderDetailsMapper;
import com.deyang.workflow.service.IWorkOrderBaseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.deyang.workflow.untils.IdUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sun.nio.ch.Util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 工单信息表 服务实现类
 * </p>
 *
 * @author zhanghuaiyu
 * @since 2021-07-01
 */
@Service
@Transactional
@Slf4j
public class WorkOrderBaseServiceImpl extends ServiceImpl<WorkOrderBaseMapper, WorkOrderBase> implements IWorkOrderBaseService {

    @Autowired
    private WorkOrderBaseMapper workOrderBaseMapper;

    @Autowired
    private WorkOrderDetailsMapper workOrderDetailsMapper;

    @Override
    public IPage<WorkOrderBase> getWorkOrder(WorkOrderBase workOrderBase) {

        //分页条数插入
        Page<WorkOrderBase> page = new Page<>(workOrderBase.getPageIndex(), workOrderBase.getPageSize());
        IPage<WorkOrderBase> workOrder = null;
        //1.判断工单是设备工单还是人工工单,0是设备工单，1是人工工单
        if (StringUtils.isNotEmpty(workOrderBase.getWorkOrderType())) {
            workOrder = workOrderBaseMapper.getWorkOrder(page, workOrderBase);
        }

        return workOrder;
    }

    @Override
    public void saveWorkOrder(WorkOrderBase workOrderBase) {
        try {
            SimpleDateFormat df = new SimpleDateFormat(DatePattern.PURE_DATETIME_PATTERN);//设置日期格式
            String format = df.format(new Date());
            Random r = new Random();
            format = format + r.nextInt(100);
            log.info("=====================" + "工单编号为" + format);
            workOrderBase.setWorkOrderId(format);
            workOrderBase.setCreator("zhanghuaiyu");//提及人信息
            workOrderBase.setCreateTime(new Date());//创建时间
            //新增到工单基础信息表
            //确实当前提交人
            workOrderBaseMapper.insert(workOrderBase);
            log.info("=====================" + "插入工单基础表的信息到work_order_base表成功" + workOrderBase.toString());
            //更新到工单步骤表
            WorkOrderDetails details = new WorkOrderDetails();
            details.setWorkOrderId(workOrderBase.getWorkOrderId());//工单编号
            details.setWorkOrderName(workOrderBase.getWorkOrderName());//工单名称
            details.setNodeName("提交工单");//节点名称
            details.setProcessMode("0");//处理方式 1是手工单,2是设备自动单
            details.setCreateTime(new Date());//创建时间
            details.setCreator("zhanghuaiyu");//创建人信息
            details.setRedeployStatus("0");//是否存在转派申请，0为否，1为是
            details.setStatus("0");//o为未处理，1为已处理
            //处理图片信息,将图片存到指定的位置，数据库存入图片的地址
            if (null != workOrderBase.getListImg() && workOrderBase.getListImg().size() > 0) {
                GetImg(workOrderBase.getListImg(), details);

            }
            workOrderDetailsMapper.insert(details);
            log.info("=====================" + "插入工单基础表的信息到work_order_details表成功" + workOrderBase.toString());

        } catch (Exception e) {
            log.error("========================" + "工单信息新增失败" + e.getMessage());
        }


    }

    @Override
    public WorkOrderBase queryWorkOrder(String workOrderId) {
        WorkOrderBase workOrderBase = null;
        try {
            log.info("===========================" + "查询工单的基础信息workOrderId" + workOrderId);
            //根据传入的工单id获取相应的工单基础信息
            workOrderBase = workOrderBaseMapper.selectById(workOrderId);
            log.info("===========================" + "工单号查询工单基础信息成功");
        } catch (Exception e) {
            log.error("==================================" + e.getMessage());
        }
        return workOrderBase;
    }

    public void GetImg(List<String> list, WorkOrderDetails details) {

        String uuid = IdUtils.simpleUUID();
        for (int i = 0; i < list.size(); i++) {

            /**
             * 1.获取到后面到数据
             */
            String data = list.get(i);
            String base64Data = data.split(",")[1];
            /**
             * 2.解码成字节数组
             */
            Base64.Decoder decoder = Base64.getDecoder();
            byte[] bytes = decoder.decode(base64Data);
            /**
             * 3.字节流转文件
             */
            FileOutputStream fos = null;
            String filePath = null;
           /*图片存入数据库需要做特殊处理：目前逻辑如下：
                根据当前用户来区分，创建一个当前用户的文件夹，生成一个唯一的id作为文件夹，将图片的信息
                存入到改文件夹下面，数据库地址存指定的路径+用户文件夹+唯一id文件夹
           *
           * */
            File file = new File("D:/zhanghuaiyu/" + uuid);//创建用户下的文件,zhanghuaiyu为后期用户信息替换
            if (!file.exists()) {
                file.mkdirs();
            }

            //拼接图片顺序，目的是方便返回图片信息时排序
            filePath = file + "\\" + i + ".jpg";
            details.setPhotoPath(file.getPath());
            try {
                fos = new FileOutputStream(filePath);
                fos.write(bytes);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

}
